package cn.steel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.domain.entity.User;
import cn.steel.mapper.SupplierInfoMapper;
import cn.steel.mapper.UserMapper;
import cn.steel.service.SupplierInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class SupplierInfoServiceImpl implements SupplierInfoService {

    private final SupplierInfoMapper supplierInfoMapper;
    private final UserMapper userMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String TOP10_CACHE_KEY = "supplier:ranking:top10";

    @Value("${file.save-dir}")
    private String SAVE_DIR;

    @Value("${file.access-prefix}")
    private String ACCESS_PREFIX;

    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

    @Override
    public SupplierInfo getSupplierInfoByUserId(Long userId) {
        User user = userMapper.findUserById(userId);
        if (user == null || !"SUPPLIER".equals(user.getRole())) {
            throw new IllegalArgumentException("供应商不存在或用户角色不正确");
        }
        SupplierInfo supplierInfo = supplierInfoMapper.findByUserId(userId);
        if (supplierInfo == null) {
            throw new IllegalArgumentException("供应商信息未初始化");
        }
        // 计算星级
        supplierInfo.calculateStars();
        log.info("Fetched SupplierInfo for userId={}: averageRating={}, fullStars={}, hasHalfStar={}",
                userId, supplierInfo.getAverageRating(), supplierInfo.getFullStars(), supplierInfo.getHasHalfStar());
        return supplierInfo;
    }
    @Override
    @Transactional
    public void updateSupplierInfo(SupplierInfo supplierInfo, MultipartFile logoFile, MultipartFile licenseFile) {
        User user = userMapper.findUserById(supplierInfo.getUserId());
        if (user == null || !"SUPPLIER".equals(user.getRole())) {
            throw new IllegalArgumentException("供应商不存在或用户角色不正确");
        }
        SupplierInfo existing = supplierInfoMapper.findByUserId(supplierInfo.getUserId());
        if (existing == null) {
            throw new IllegalArgumentException("供应商信息未初始化");
        }

        // 处理 logo 文件
        if (logoFile != null && !logoFile.isEmpty()) {
            if (existing.getLogoUrl() != null) {
                deleteFile(existing.getLogoUrl());
            }
            String logoPath = saveFile(logoFile, "logo_", ".jpg,.png");
            supplierInfo.setLogoUrl(logoPath);
        } else {
            supplierInfo.setLogoUrl(existing.getLogoUrl());
        }

        // 处理营业执照文件
        if (licenseFile != null && !licenseFile.isEmpty()) {
            if (existing.getLicenseUrl() != null) {
                deleteFile(existing.getLicenseUrl());
            }
            String licensePath = saveFile(licenseFile, "license_", ".pdf");
            supplierInfo.setLicenseUrl(licensePath);
        } else {
            supplierInfo.setLicenseUrl(existing.getLicenseUrl());
        }
        // 保留现有 averageRating 和 auditStatus
        supplierInfo.setAverageRating(existing.getAverageRating());
        supplierInfo.setAuditStatus(existing.getAuditStatus());

        supplierInfoMapper.updateSupplierInfo(supplierInfo);
        log.info("供应商信息更新成功: userId={}", supplierInfo.getUserId());
    }

    @Override
    public List<SupplierInfo> findAllPaginated(String search) {
        return supplierInfoMapper.findAllPaginated(search);
    }


    private String saveFile(MultipartFile file, String prefix, String allowedExtensions) {
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小超过限制（10MB）");
        }
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase() : "";
        if (!allowedExtensions.contains(extension)) {
            throw new IllegalArgumentException("不支持的文件类型，仅允许: " + allowedExtensions);
        }
        String uniqueFileName = prefix + UUID.randomUUID() + extension;

        File dest = new File(SAVE_DIR + uniqueFileName);
        if (!dest.getParentFile().exists()) {
            boolean created = dest.getParentFile().mkdirs();
            if (!created) {
                throw new RuntimeException("无法创建保存目录: " + dest.getParentFile().getAbsolutePath());
            }
        }
        try {
            file.transferTo(dest);
            log.info("文件保存成功: {}", dest.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败: " + e.getMessage(), e);
        }
        return ACCESS_PREFIX + uniqueFileName;
    }

    private void deleteFile(String filePath) {
        File file = new File(SAVE_DIR + filePath.substring(ACCESS_PREFIX.length()));
        if (file.exists() && file.delete()) {
            log.info("Deleted file: {}", file.getPath());
        } else {
            log.warn("Failed to delete file: {}", file.getPath());
        }
    }

    @Override
    public List<SupplierInfo> getTop10Suppliers() {
        // 尝试从 Redis 获取缓存
        List<SupplierInfo> cachedSuppliers = (List<SupplierInfo>) redisTemplate.opsForValue().get(TOP10_CACHE_KEY);
        if (cachedSuppliers != null && !cachedSuppliers.isEmpty()) {
            log.info("从 Redis 缓存获取供应商排行榜: key={}, 数量={}", TOP10_CACHE_KEY, cachedSuppliers.size());
            return cachedSuppliers;
        }

        // 缓存不存在，从数据库查询
        List<SupplierInfo> suppliers = supplierInfoMapper.findTop10ByAverageRating();
        if (suppliers == null) {
            suppliers = new ArrayList<>(); // 确保不返回 null
        }
        log.info("从数据库查询供应商排行榜: 数量={}", suppliers.size());

        // 存入 Redis 缓存，设置 1 小时有效期
        redisTemplate.opsForValue().set(TOP10_CACHE_KEY, suppliers, 1, TimeUnit.HOURS);
        log.info("供应商排行榜已缓存到 Redis: key={}", TOP10_CACHE_KEY);

        return suppliers;
    }
    @Override
    public SupplierInfo getSupplierInfoById(Long supplierId) {
        return supplierInfoMapper.getSupplierInfoById(supplierId);
    }
}